package oaSystem.web.controller.rest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import oaSystem.biz.DocumentBiz;
import oaSystem.entity.Document;
import oaSystem.entity.Employee;
import oaSystem.web.security.Authorize;

@RequestMapping("/api/document")
@RestController
public class Rest_DocumentController {
	@Autowired
	private DocumentBiz documentBiz;
	
	@Authorize(rules="document-list")
	@RequestMapping(value="/loadTree")
	public String loadTree(HttpServletResponse res) throws IOException{
		List<Document> findAllDocment = documentBiz.findAllDocment();
		StringBuffer sb = new StringBuffer();
		sb.append("[{ \"id\":\"0\" , \"parent\":\"#\", \"text\":\"公司资料\" },");
		for (Document d:findAllDocment) {
			if("FOLDER".equals(d.getType())){
				sb.append(" {\"id\":\""+d.getId()+"\" , \"parent\":\""+d.getParentId()+"\" , \"text\":\""+d.getName()+"\" , \"type\":\""+d.getType()+"\"},");
			}
		}
		sb.deleteCharAt(sb.length()-1);
		sb.append("]");
		return sb.toString();
	}
	@Authorize(rules="document-list")
	@RequestMapping(value="/fileByParentId")
	public Map<String, Object> loadFileByParentId(@RequestParam(value="parentId",defaultValue="0")Integer parentId){
		Map<String,Object> map = new HashMap<String,Object>();
		List<Document> documentByParentId = documentBiz.findByParentId(parentId);
		map.put("data", documentByParentId);
		map.put("recordsTotal",documentByParentId.size());
		map.put("recordsFiltered",documentByParentId.size());
		return map;
	}
	@Authorize(rules="document-download")
	@RequestMapping(value="/download")
	public void download(String fileName,HttpServletResponse response,HttpServletRequest request) throws IOException{
		//设置文件MIME类型  
        response.setContentType(request.getServletContext().getMimeType(fileName));  
        //设置Content-Disposition  
        response.setHeader("Content-Disposition", "attachment;filename="+fileName);  
        //读取目标文件，通过response将目标文件写到客户端  
        //获取目标文件的绝对路径  
        String fullFileName = request.getServletContext().getRealPath(fileName);
        //读取文件  
        InputStream in = new FileInputStream(fullFileName);  
        OutputStream out = response.getOutputStream(); 
        //写文件  
        int b;  
        while((b=in.read())!= -1){  
            out.write(b);  
        }
        in.close();  
        out.close();  
	}
	@Authorize(rules="document-upload")
	@RequestMapping(value="/upload",method=RequestMethod.POST)
	public void upload(Document document, MultipartFile uploadFile, HttpServletRequest req,HttpSession session) throws IOException{
		//getDescription();
		//getName();
		//getParentId();
		//getId();//由数据库自增
		//以上属性不用填写
		if(!uploadFile.isEmpty()){
			//上传文件
			String uploadFileName = uploadFile.getOriginalFilename();//上传文件的文件名
			String fileType = uploadFileName.substring(uploadFileName.lastIndexOf(".")+1);//文件类型
			String vpath = "/upload/"+uploadFileName;//虚拟路径
			String path = req.getServletContext().getRealPath(vpath);//真实路径
			byte[] data = uploadFile.getBytes();//打散变成bytes数组
			File file = new File(path);
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(data);
			fos.flush();
			fos.close();
			//插数据库表
			Employee employee =(Employee)session.getAttribute("user");//当前session用户
			document.setCreator(employee);
			document.setCreateTime(new Date());//创建日期
			document.setFileUrl(vpath);//虚拟路径
			document.setType(fileType);//文件类型
			documentBiz.addFile(document);
		}
	}
	
	@Authorize(rules="document-delete")
	@RequestMapping(value="/delete/{fileId}",method=RequestMethod.POST)
	public void delete(@PathVariable(value="fileId") int fileId){
		List<Integer> arrayList = new ArrayList<Integer>();
		arrayList.add(fileId);
		documentBiz.deleteFile(arrayList);
	}
	@Authorize(rules="document-add")
	@RequestMapping(value="/addFolder",method=RequestMethod.POST)
	public void addFolder(Document document,HttpSession session){
		Employee employee =(Employee)session.getAttribute("user");//当前session用户
		document.setCreator(employee);
		document.setCreateTime(new Date());
		document.setType("FOLDER");
		documentBiz.addFolder(document);
	}
}
